<?php


// no direct access
defined('_JEXEC') or die('Restricted access');

if (!defined('modSubMenuXMLCallbackDefined')) {
	function modSubMenuXMLCallback(& $node, $args) {
		
		$user = & JFactory :: getUser();
		$menu = & JSite :: getMenu();
		$active = $menu->getActive();
		$path = isset ($active) ? array_reverse($active->tree) : null;

		if (($args['end']) && ($node->attributes('level') >= $args['end'])) {
			$children = $node->children();
			foreach ($node->children() as $child) {
				if ($child->name() == 'ul') {
					$node->removeChild($child);
				}
			}
		}

		if ($node->name() == 'ul') {
			
			// Rimozione voci non autorizzate
			foreach ($node->children() as $child) {
				if ($child->attributes('access') > $user->get('aid', 0)) {
					$node->removeChild($child);
				}
			}

			// Ultimo figlio aggiungo classe last
			$child = $node->children();
			$child = $child[count($child) -1];
			if ($child->attributes('class')) {
				$child->addAttribute('class', $child->attributes('class') . ' last');
			} else {
				$child->addAttribute('class', 'last');
			}

		}

		if (($node->name() == 'li') && isset ($node->ul)) {
			if ($node->attributes('class')) {
				$node->addAttribute('class', $node->attributes('class') . ' parent');
			} else {
				$node->addAttribute('class', 'parent');
			}
		}
		
		// Check nodo processato in albero di navigazione percorso
		if (isset ($path) && in_array($node->attributes('id'), $path)) {
			if ($node->attributes('class')) {
				$node->addAttribute('class', $node->attributes('class') . ' active');
			} else {
				$node->addAttribute('class', 'active');
			}
		} else {
			
			// Se albero non esploso sempre
			if (isset ($args['children']) && !$args['children']) {
				$children = $node->children();
				// Rimozione figli da nodi non in albero correntemente esplorato 
				foreach ($node->children() as $child) {
					if ($child->name() == 'ul') {
						$node->removeChild($child);
					}
				}
			}
		}

		if (($node->name() == 'li') && ($id = $node->attributes('id'))) {
			if ($node->attributes('class')) {
				$node->addAttribute('class', $node->attributes('class') . ' item' . $id);
			} else {
				$node->addAttribute('class', 'item' . $id);
			}
		}

		if(in_array($node->attributes('id'), $path)) {
			if ($node->attributes('class')) {
				$node->addAttribute('class', $node->attributes('class') . ' selected');
			} else {
				$node->addAttribute('class', 'selected');
			}
		}

		if (isset ($path) && $node->attributes('id') == $path[0]) {
			$node->addAttribute('id', 'current');
			
		} else {
			$node->removeAttribute('id');
		}
		$node->removeAttribute('level');
		$node->removeAttribute('access');
	}
	define('modSubMenuXMLCallbackDefined', true);
}

// Catturo output base del mod_mainmenu
modMainMenuHelper::render($params, 'modSubMenuXMLCallback');